package com.fs.system.exception;

import com.fs.system.common.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局异常处理捕获器
 */
//标识全局异常处理器并设置捕获路径
//因为异常产生最终都会归宿到controller中，所有异常统一在controller包中接口中处理。
@ControllerAdvice
public class GlobalExceptionHandler {

    // 修改HTTP状态码为500
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseData handleException(Exception e) {
        e.printStackTrace();
        return new ResponseData("500", "系统繁忙，请稍后再试");
    }

    @ExceptionHandler(CustomerException.class)
    @ResponseBody
    public ResponseData handleCustomerException(CustomerException e) {
        return new ResponseData(e.getCode(), e.getMsg());
    }

    // 新增数据库连接异常处理
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE) // 503
    @ExceptionHandler(CannotGetJdbcConnectionException.class)
    @ResponseBody
    public ResponseData handleDbException() {
        return new ResponseData("503", "系统维护中，请稍后再试");
    }
}
